package api

import (
	"openapi.itspire.cn/common/dict"
	"openapi.itspire.cn/common/throw"
	"openapi.itspire.cn/database"
	"openapi.itspire.cn/model"
	"openapi.itspire.cn/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

func CommentList(c *gin.Context) {
	var comment model.Comment
	var user model.User

	articleId, _ := strconv.Atoi(c.DefaultQuery("article", "0"))
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	//size := global.PageSize

	userInfo := utils.GetUserInfo(c)
	id, _ := strconv.Atoi(utils.TypeAssertion(userInfo["id"]))

	total := 0
	query := database.Ins.
		Model(&comment).
		Where("article_id = ? AND status = ? AND delete_time = ?", articleId, dict.StatusOn, dict.DeleteNot)

	if id > 0 {
		// 登录用户可以看到自己所有的评论
		query = query.Or("article_id = ? AND user_id = ?", articleId, id)
	}

	if err := query.Count(&total).Error; err != nil {
		throw.ServerError(c, err.Error())
		return
	}

	list := make([]map[string]interface{}, 0)
	if total > 0 {
		comments := make([]model.Comment, 0)
		queryComment := database.Ins.
			Table(comment.GetTableName() + " a").
			Select("a.id,a.tid,a.pid,a.user_id,a.nickname,a.content,a.create_time,b.id as reply_id,b.nickname as reply_nickname,c.avatar").
			Joins("left join "+comment.GetTableName()+" b on a.pid = b.id").
			Joins("left join "+user.GetTableName()+" c on a.user_id = c.id").
			Where("a.article_id = ? AND a.status = ? AND a.delete_time = ? AND c.status < ? AND c.delete_time = ?", articleId, dict.StatusOn, dict.DeleteNot, dict.StatusNopass, dict.DeleteNot)

		if id > 0 {
			// 登录用户可以看到自己所有的评论
			queryComment = queryComment.Or("a.article_id = ? AND a.user_id = ?", articleId, id)
		}

		//queryComment = queryComment.Order("a.id desc")
			//Limit(size).
			//Offset((page - 1) * size)
		if err := queryComment.Scan(&comments).Error; err != nil {
			panic(err)
		}
		list = comment.GetFormatComment(comments)
	}


	maps := make(map[string]interface{})
	maps["pagination"] = map[string]int{"page": page, "size": total, "total": total}
	maps["list"] = list

	utils.Success(c, maps)
}

func CommentNew(c *gin.Context) {
	var comment model.Comment
	size := 3

	comments := make([]model.Comment, 0)
	queryComment := database.Ins.
		Table(comment.GetTableName() + " a ").
		Select("max(a.id) as id,a.article_id,SUBSTRING_INDEX(GROUP_CONCAT(a.content order by a.id desc),',',1) as content,SUBSTRING_INDEX(GROUP_CONCAT(a.nickname order by a.id desc),',',1) as nickname,b.title").
		Joins("left join "+model.Article{}.GetTableName()+" b on a.article_id = b.id").
		Where("a.article_id > ? AND a.pid = ? AND a.status = ? AND a.delete_time = ? AND b.status = ? AND b.delete_time = ?", 0, 0, dict.StatusOn, dict.DeleteNot, dict.StatusOn, dict.DeleteNot)

	userInfo := utils.GetUserInfo(c)
	id, _ := strconv.Atoi(utils.TypeAssertion(userInfo["id"]))
	if id > 0 {
		// 登录用户可以看到自己的评论
		queryComment = queryComment.Or("a.article_id > ? AND a.pid = ? AND a.user_id = ? AND b.status = ? AND b.delete_time = ?", 0, 0, id, dict.StatusOn, dict.DeleteNot)
	}

	queryComment = queryComment.Group("a.article_id").
		Order("a.id desc").
		Limit(size)
	if err := queryComment.Scan(&comments).Error; err != nil {
		panic(err)
	}
	utils.Success(c, comments)
}

func CommentCreate(c *gin.Context) {
	var comment model.Comment

	userInfo := utils.GetUserInfo(c)
	id, _ := strconv.Atoi(utils.TypeAssertion(userInfo["id"]))
	nickname := utils.TypeAssertion(userInfo["nickname"])
	if id == 0 {
		throw.AuthException(c, "账号尚未激活")
		return
	}

	if err := c.ShouldBindJSON(&comment); err != nil {
		throw.ParameterError(c, err.Error())
		return
	}

	timestamp := uint64(time.Now().Unix())


	// 新增评论
	ip, _ := utils.Ip2Long(c.ClientIP())
	comment.Ip = ip
	comment.UserId = uint64(id)
	comment.Nickname = nickname
	comment.CreateTime = timestamp

	res := database.Ins.NewRecord(comment)
	if res {
		database.Ins.Create(&comment)
		if comment.Pid == 0 {
			database.Ins.Model(&comment).Update("tid", comment.Id)
		}
	}

	// 文章评论审核通过+1
	if comment.ArticleId > 0 && comment.Status == dict.StatusOn {
		var article model.Article
		database.Ins.Model(&article).
			Where("id = ? AND status = ? AND delete_time = ?", comment.ArticleId, dict.StatusOn, dict.DeleteNot).
			UpdateColumn("comment_num", gorm.Expr("comment_num + ?", 1))
	}

	utils.Success(c, nil)
}
